package com.example.cardstackproject.card

import android.view.View
import androidx.viewpager.widget.ViewPager
import kotlin.math.abs
import kotlin.math.floor

/**
 * 叠加卡片效果
 * Created by Acorn on 2017/12/29.
 */
class OverlayTransformer : ViewPager.PageTransformer {
    private var scaleOffset = 80f // 表示页面缩放时的偏移量
    private var transOffset = 100f //表示页面平移时的偏移量,值约大,图片之间的间隙更宽
    var overlayCount: Int //表示页面堆叠的数量，即最多可以看到多少个页面同时出现在屏幕上
        private set

    constructor(overlayCount: Int) {
        this.overlayCount = overlayCount
    }

    constructor(overlayCount: Int, scaleOffset: Float, transOffset: Float) {
        this.overlayCount = overlayCount
        if (java.lang.Float.compare(scaleOffset, -1f) != 0) this.scaleOffset = scaleOffset
        if (java.lang.Float.compare(transOffset, -1f) != 0) this.transOffset = transOffset
    }

    /**
     *
     * @param page Apply the transformation to this page
     * @param position 参数表示页面相对于中心点的位置，正值表示向右滑动，负值表示向左滑动
     */
    override fun transformPage(page: View, position: Float) {
        if (position <= 0.0f) { //当前页
            page.translationX = 0f
            page.alpha = (1 - 0.5f * abs(position.toDouble())).toFloat()
            page.isClickable = true
        } else {
            otherTrans(page, position)
            page.isClickable = false
        }
    }

    private fun otherTrans(page: View, position: Float) {
        //缩放比例
        val scale = (page.width - scaleOffset * position) / page.width.toFloat()
        page.scaleX = scale
        page.scaleY = scale

        page.alpha = 1f
        if (position > overlayCount - 1 && position < overlayCount) { //当前页向右滑动时,最右面第四个及以后页面应消失
            val curPositionOffset = transOffset * floor(position.toDouble())
                .toFloat() //向下取整
            val lastPositionOffset = transOffset * floor((position - 1).toDouble())
                .toFloat() //上一个卡片的偏移量
            val singleOffset = (1 - abs((position % position.toInt()).toDouble())).toFloat()
            val transX =
                (-page.width * position) + (lastPositionOffset + singleOffset * (curPositionOffset - lastPositionOffset))
            page.translationX = transX
        } else if (position <= overlayCount - 1) {
            val transX = (-page.width * position) + (transOffset * position)
            page.translationX = transX
        } else {
            page.alpha = 0f
            //            page.setTranslationX(0); //不必要的隐藏在下面
        }
    }
}
